<?php

namespace App\Console\Commands;

use App\Dao\CommonDao;
use App\Dao\OrdersDao;
use App\Dao\UsersDao;
use Illuminate\Console\Command;

class UserLevelTong extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'user_level_tong';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '用户等级同步补充';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
        $l_arr = [0,3,4,5,6,7,8];
        $yeJi = [0,26000,78000,260000,1300000,5200000,15600000];

        //查询所有用户
        $users = UsersDao::builder_user_query([])->orderByDesc('created_at')->get()->toArray();
        foreach ($users as $value){
            $spread_id = $value['spread_id'];
            while(true){
                if($spread_id == 0){
                    break;
                }
                //查询上级用户的下级数量
                $cCount = UsersDao::builder_user_query([
                    'spread_id'=>$spread_id
                ])->where('vip_index_level',1)->count();

                $u_spreadInfo = UsersDao::builder_user_query([
                    'user_id'=>$spread_id
                ])->first()->toArray();
                if($u_spreadInfo['vip_level'] == 6){
                    break;
                }
                if($cCount < $l_arr[$u_spreadInfo['vip_level']+1]){

                    break;
                }

                //查询业绩
                //业绩活口
                $yeJiMaxBe = $yeJi[$u_spreadInfo['vip_level']+1];
                if($u_spreadInfo['all_prices'] < $yeJiMaxBe){
                    break;
                }
                //获取直推的最大业绩
                $max_all_prices = OrdersDao::getMaxPrices($spread_id);
                //小区业绩只和必须大于大区1/2自己的业绩减去下级最大业绩
                $Ji = $u_spreadInfo['all_prices'];
                $MaxPrij = $max_all_prices;
                $xiaoJi = bcsub($Ji,$MaxPrij,2);
                if($xiaoJi < bcmul($MaxPrij,0.5,2)){
                    break;
                }



                UsersDao::builder_user_query([
                    'user_id'=>$spread_id
                ])->update([
                    'vip_level'=>$u_spreadInfo['vip_level']+1
                ]);
                $spread_id = UsersDao::builder_user_query([
                    'user_id'=>$spread_id
                ])->value('spread_id');
            }
        }
    }
}
